package me.sapling.single;

import java.util.HashSet;
import java.util.Set;

/**
 * @author sapling
 */
public class PigLatin {

	private static Set<String> consonants = new HashSet<>();
	static {
		String str[] = {
				"sh", "ch", "th", "ph", "wh", "tr", "dr", "qu",
				"b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
				"n", "p", "r", "s", "t", "v", "w", "x", "y", "z"
		};
		for (String tmp :
				str) {
			consonants.add(tmp);
		}
	}

	private static String src;
	private static String des;
	
	public static String doWorkWithSentence(String sentence) {
		StringBuilder tmp = new StringBuilder("");
		String[] words = sentence.split(" ");
		for (String word :
				words) {
			tmp.append(doWork(word) + " ");
		}
		tmp.deleteCharAt(tmp.length() - 1);
		return tmp.toString();
	}

	public static String doWork(String src) {
		PigLatin.src = src;
		if (src == null || "".equals(src.trim())) {	// trim() 返回的是另外一个字符串!
			des = "";
		} else {
			resolutionA();
		}
		return des;
	}

	private static void resolutionA() {
		boolean b = false;	// 用于判断是否有辅音开头的字母/字母组
		String prefix = "";
		StringBuilder tmp = new StringBuilder(src);

		char c = '\0';
		if (src.matches("\\w*\\W$")) {
			c = tmp.charAt(tmp.length()-1);
			tmp.deleteCharAt(tmp.length()-1);
		}					// 判断该单词是否包含符号

		if (tmp.length() >= 2) {
			prefix = tmp.substring(0, 2);
			b = consonants.contains(prefix.toLowerCase());
		}
		if (!b) {
			prefix = tmp.substring(0, 1);
			b = consonants.contains(prefix.toLowerCase());
		}
		if (b) {
			for (int i = 0; i < prefix.length(); i++) {
				tmp.deleteCharAt(0);
			}
			tmp.append("-" + prefix);
		} else {
			tmp.append("-");
		}
		tmp.append("ay");
		if ('\0' != c) {
			tmp.append(c);
		}
		des = tmp.toString();
	}

}
